<template>
  <div class="login-container">
    <!-- 欢迎文字 -->
    <div class="welcome-text">
      <h1>欢迎登录MES系统</h1>  
    </div>

    <!-- 登录卡片 -->
    <el-card class="login-card">
      <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="auto" class="demo-ruleForm">
        <el-form-item label="账号" prop="AccountName">
          <el-input v-model="ruleForm.AccountName" autocomplete="off" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" prop="AccountPwd">
          <el-input v-model="ruleForm.AccountPwd" show-password autocomplete="off" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="验证码" prop="captcha">
          <div class="captcha-container">
            <el-input 
              v-model="ruleForm.captcha" 
              autocomplete="off" 
              placeholder="请输入计算结果" 
              class="captcha-input"
            />
            <div class="captcha-question" @click="generateCaptcha">
              {{ captchaQuestion }}
            </div>
          </div>
        </el-form-item>
        <el-form-item label="是否记住密码: ">
          <el-switch v-model="ruleForm.Remember" class="ml-2" inline-prompt
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" active-text="记住密码"
            inactive-text="忘记密码" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)" class="login-btn">
            登录
          </el-button>
          <el-button @click="resetForm(ruleFormRef)" class="cancel-btn">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 动态流光背景 -->
    <div class="login-bg">
      <div class="bg-gradient"></div>
      <div class="light-flow light-flow-1"></div>
      <div class="light-flow light-flow-2"></div>
      <div class="light-flow light-flow-3"></div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { useCounterStore } from '@/stores/counter';
const pinia = useCounterStore();  //前端数据存储
const router = useRouter();
const ruleFormRef = ref<FormInstance>();

// 验证码相关
const captchaQuestion = ref('');
const captchaAnswer = ref(0);

onMounted(() => {
  GetLoginInfo();
  generateCaptcha(); // 页面加载时生成验证码
})

const ruleForm = reactive({
  AccountName: "",
  AccountPwd: "",
  Remember: false,
  captcha: "" // 添加验证码字段
})

// 生成随机数字
const getRandomNumber = (min: number, max: number): number => {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// 生成随机运算符
const getRandomOperator = (): string => {
  const operators = ['+', '-', '*', '/'];
  return operators[Math.floor(Math.random() * operators.length)];
}

// 生成验证码
const generateCaptcha = () => {
  const num1 = getRandomNumber(1, 10);
  const num2 = getRandomNumber(1, 10);
  const operator = getRandomOperator();
  
  // 确保除法结果为整数
  if (operator === '/') {
    const product = num1 * num2;
    captchaQuestion.value = `${product} ÷ ${num1} = ?`;
    captchaAnswer.value = num2;
  } else {
    captchaQuestion.value = `${num1} ${operator} ${num2} = ?`;
    switch (operator) {
      case '+':
        captchaAnswer.value = num1 + num2;
        break;
      case '-':
        captchaAnswer.value = num1 - num2;
        break;
      case '*':
        captchaAnswer.value = num1 * num2;
        break;
    }
  }
  
  // 清空输入框
  ruleForm.captcha = "";
}

//反填账号和密码
const GetLoginInfo = () => {
  if (pinia.Logininfo.uid != "")
    ruleForm.Remember = true;
  ruleForm.AccountName = pinia.Logininfo.uid;
  ruleForm.AccountPwd = pinia.Logininfo.pwd;
}

const rules = reactive<FormRules<typeof ruleForm>>({
  AccountName: [
    { required: true, message: '请输入账号', trigger: 'blur' },
  ],
  AccountPwd: [
    { required: true, message: '请输入密码', trigger: 'blur' },
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value && parseInt(value) !== captchaAnswer.value) {
          callback(new Error('验证码错误'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
})
//登录
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      axios.get("/api/Accounts/Login", {
        params: {
          AccountName: ruleForm.AccountName,
          AccountPwd: ruleForm.AccountPwd
        }
      }).then(res => {
        if (res.data.code == 200) {
          ElMessage.success(res.data.message)
          // 设置Pinia状态
          pinia.piniaDto.accountName = res.data.data.accountName;
          pinia.piniaDto.realName = res.data.data.realName;
          pinia.piniaDto.roleName = res.data.data.roleNmae;
          pinia.piniaDto.tokenstr = res.data.data.tokenstr;
          pinia.piniaDto.IsLoign = true; // 设置登录状态为true
          
          // 登录成功，写JWT的 token到本地
          window.localStorage.setItem("token", res.data.data.tokenstr);
          
          // 数据提交后端要加入新的Token值
          axios.defaults.headers.common["Authorization"] =
            "Bearer " + res.data.data.tokenstr;
          
          //记住密码
          if (ruleForm.Remember == true) {
            pinia.Logininfo.uid = ruleForm.AccountName;
            pinia.Logininfo.pwd = ruleForm.AccountPwd;
          }
          else {
            pinia.Logininfo.uid = "";
            pinia.Logininfo.pwd = "";
          }
          
          // 登录成功后跳转到工作台
          router.push("/Dashboard")
        }
        else {
          ElMessage.error(res.data.message)
          // 登录失败时刷新验证码
          generateCaptcha();
        }
      })
    }
  })
}
//重置
const resetForm = (formEl: FormInstance | undefined) => {
  ruleForm.Remember = false;
  if (!formEl) return
  formEl.resetFields()
  // 重置时重新生成验证码
  generateCaptcha();
}
</script>

<style scoped>
/* 全局样式重置 */
:deep(*) {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 登录容器 */
.login-container {
  position: relative;
  width: 100vw;
  min-height: 100vh;
  /* 改为最小高度，允许内容超出时滚动 */
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  /* 改为从顶部开始布局 */
  align-items: center;
  overflow-x: hidden;
  /* 只隐藏水平滚动 */
  overflow-y: auto;
  /* 允许垂直滚动 */
  padding: 60px 20px 40px;
  /* 添加顶部和底部内边距 */
  box-sizing: border-box;
}

/* 欢迎文字 */
.welcome-text {
  position: relative;
  /* 改为相对定位，参与正常文档流 */
  text-align: center;
  z-index: 10;
  animation: fadeInUp 1s ease-out;
  margin-bottom: 40px;
  /* 与登录卡片之间的间距 */
  margin-top: 20px;
  /* 顶部间距 */
  flex-shrink: 0;
  /* 防止被压缩 */
}

.welcome-text h1 {
  font-size: 3.5rem;
  font-weight: bold;
  color: #ff6b35;
  text-shadow: 0 0 20px rgba(255, 107, 53, 0.6), 0 0 40px rgba(255, 107, 53, 0.3);
  margin: 0;
  animation: pulse 2s infinite;
}

/* 登录卡片 */
.login-card {
  position: relative;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 20px 60px rgba(255, 107, 53, 0.15), 0 0 0 1px rgba(255, 107, 53, 0.05);
  border: 1px solid rgba(255, 107, 53, 0.2);
  backdrop-filter: blur(10px);
  z-index: 20;
  max-width: 480px;
  width: 90%;
  animation: fadeIn 0.8s ease-out 0.2s both;
  transition: all 0.3s ease;
  flex-shrink: 0;
  /* 防止被压缩 */
  margin-bottom: 20px;
  /* 底部间距，确保在小屏幕时不贴边 */
}

.login-card:hover {
  box-shadow: 0 25px 70px rgba(255, 107, 53, 0.25), 0 0 0 1px rgba(255, 107, 53, 0.1);
  transform: translateY(-5px);
}

/* 表单样式 */
.demo-ruleForm {
  width: 100%;
}

/* 统一表单项布局 - 标签左对齐，内容区域有间距 */
:deep(.el-form-item) {
  margin-bottom: 24px !important;
}

:deep(.el-form-item__label) {
  color: #ff6b35 !important;
  font-weight: 500 !important;
  font-size: 14px !important;
  line-height: 1.5 !important;
  text-align: left !important;
  padding-right: 16px !important;
  /* 标签与内容之间的空隙 */
  margin-bottom: 8px !important;
  width: auto !important;
  min-width: 120px !important;
  /* 确保标签有足够宽度对齐 */
}

/* 账号和密码标签特殊对齐 - 与"是否记住密码"的"是"字对齐 */
:deep(.el-form-item:nth-child(1) .el-form-item__label),
:deep(.el-form-item:nth-child(2) .el-form-item__label) {
  padding-left: 0px !important;
  /* 移除左边距，让"账"、"密"、"是"三字对齐 */
  text-indent: 0px !important;
  /* 确保文字从最左边开始 */
}

/* 确保"是否记住密码"标签也从最左边开始 */
:deep(.el-form-item:nth-child(3) .el-form-item__label) {
  padding-left: 0px !important;
  text-indent: 0px !important;
}

/* 输入框样式统一 */
:deep(.el-input__wrapper) {
  border-radius: 8px !important;
  border-color: #ffb086 !important;
  transition: all 0.3s ease !important;
  padding: 12px 16px !important;
  min-height: 44px !important;
}

/* 表单项内容区域 */
:deep(.el-form-item__content) {
  margin-left: 0 !important;
}

/* 按钮区域特殊间距 */
:deep(.el-form-item:last-child) {
  margin-top: 32px !important;
  margin-bottom: 0 !important;
}

:deep(.el-input__wrapper) {
  border-radius: 8px !important;
  border-color: #ffb086 !important;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 2px rgba(255, 107, 53, 0.2) !important;
  border-color: #ff6b35 !important;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px rgba(255, 107, 53, 0.3) !important;
  border-color: #ff6b35 !important;
}

/* 记住密码区域特殊样式 */
:deep(.el-form-item:nth-child(3) .el-form-item__content) {
  display: flex !important;
  align-items: center !important;
  justify-content: flex-start !important;
  margin-top: 0 !important;
}

/* 开关组件样式 */
:deep(.el-switch) {
  --el-switch-on-color: #ff6b35 !important;
  --el-switch-off-color: #dcdfe6 !important;
  margin: 0 !important;
}

:deep(.el-switch__label) {
  color: #606266 !important;
  font-size: 13px !important;
}

:deep(.el-switch__label.is-active) {
  color: #ff6b35 !important;
}

/* 按钮区域布局 */
:deep(.el-form-item:last-child .el-form-item__content) {
  display: flex !important;
  flex-direction: column !important;
  gap: 12px !important;
}

/* 按钮样式 */
.login-btn {
  background: linear-gradient(135deg, #ff6b35 0%, #ff8e53 100%) !important;
  border: none !important;
  color: white !important;
  font-weight: 600 !important;
  padding: 12px 30px !important;
  border-radius: 8px !important;
  transition: all 0.3s ease !important;
  box-shadow: 0 4px 15px rgba(255, 107, 53, 0.3) !important;
  width: 100% !important;
  min-height: 44px !important;
}

.login-btn:hover {
  background: linear-gradient(135deg, #ff5722 0%, #ff7043 100%) !important;
  transform: translateY(-2px) !important;
  box-shadow: 0 6px 20px rgba(255, 107, 53, 0.4) !important;
}

.cancel-btn {
  border-color: #ff6b35 !important;
  color: #ff6b35 !important;
  font-weight: 500 !important;
  padding: 12px 30px !important;
  border-radius: 8px !important;
  transition: all 0.3s ease !important;
  width: 100% !important;
  min-height: 44px !important;
  background-color: transparent !important;
}

.cancel-btn:hover {
  background-color: rgba(255, 107, 53, 0.05) !important;
  border-color: #ff5722 !important;
  color: #ff5722 !important;
  transform: translateY(-1px) !important;
}

/* 动态流光背景 */
.login-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: radial-gradient(circle at center, #fff9f5 0%, #fff0e5 100%);
  overflow: hidden;
}

.bg-gradient {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background:
    radial-gradient(circle at 20% 30%, rgba(255, 160, 70, 0.2) 0%, transparent 30%),
    radial-gradient(circle at 80% 70%, rgba(255, 160, 70, 0.2) 0%, transparent 30%);
}

/* 流光效果 */
.light-flow {
  position: absolute;
  width: 300px;
  height: 300px;
  background: linear-gradient(45deg, transparent, rgba(255, 107, 53, 0.3), transparent);
  border-radius: 50%;
  filter: blur(30px);
  opacity: 0.6;
}

.light-flow-1 {
  top: -100px;
  left: -100px;
  animation: flow1 15s infinite linear;
}

.light-flow-2 {
  bottom: -100px;
  right: -100px;
  animation: flow2 18s infinite linear;
}

.light-flow-3 {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  animation: flow3 20s infinite linear;
}

/* 动画定义 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(40px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes pulse {

  0%,
  100% {
    transform: scale(1);
  }

  50% {
    transform: scale(1.05);
  }
}

@keyframes flow1 {
  0% {
    transform: translateX(0) translateY(0) rotate(0deg);
  }

  100% {
    transform: translateX(800px) translateY(800px) rotate(360deg);
  }
}

@keyframes flow2 {
  0% {
    transform: translateX(0) translateY(0) rotate(0deg);
  }

  100% {
    transform: translateX(-800px) translateY(-800px) rotate(-360deg);
  }
}

@keyframes flow3 {
  0% {
    transform: translate(-50%, -50%) scale(1) rotate(0deg);
  }

  25% {
    transform: translate(-50%, -50%) scale(1.2) rotate(90deg);
  }

  50% {
    transform: translate(-50%, -50%) scale(1) rotate(180deg);
  }

  75% {
    transform: translate(-50%, -50%) scale(0.8) rotate(270deg);
  }

  100% {
    transform: translate(-50%, -50%) scale(1) rotate(360deg);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-container {
    padding: 40px 15px 30px;
    /* 平板设备减少内边距 */
  }

  .welcome-text {
    margin-bottom: 30px;
    /* 减少与登录卡片的间距 */
    margin-top: 10px;
  }

  .welcome-text h1 {
    font-size: 2.5rem;
  }

  .login-card {
    padding: 30px 20px;
    margin: 0 10px 15px;
    /* 调整边距 */
  }

  /* 平板设备标签样式调整 */
  :deep(.el-form-item__label) {
    min-width: 100px !important;
    padding-right: 12px !important;
    font-size: 13px !important;
  }

  /* 平板设备账号密码标签对齐调整 */
  :deep(.el-form-item:nth-child(1) .el-form-item__label),
  :deep(.el-form-item:nth-child(2) .el-form-item__label),
  :deep(.el-form-item:nth-child(3) .el-form-item__label) {
    padding-left: 0px !important;
    /* 平板设备保持左对齐 */
    text-indent: 0px !important;
  }

  /* 平板设备表单项间距调整 */
  :deep(.el-form-item) {
    margin-bottom: 20px !important;
  }

  /* 平板设备按钮间距调整 */
  :deep(.el-form-item:last-child .el-form-item__content) {
    gap: 10px !important;
  }
}

@media (max-width: 480px) {
  .login-container {
    padding: 30px 10px 20px;
    /* 手机设备进一步减少内边距 */
  }

  .welcome-text {
    margin-bottom: 25px;
    /* 手机设备进一步减少间距 */
    margin-top: 5px;
  }

  .welcome-text h1 {
    font-size: 2rem;
  }

  .login-card {
    padding: 25px 15px;
    margin: 0 5px 10px;
    /* 手机设备调整边距 */
  }

  /* 手机设备标签样式调整 */
  :deep(.el-form-item__label) {
    min-width: 80px !important;
    padding-right: 10px !important;
    font-size: 12px !important;
  }

  /* 手机设备账号密码标签对齐调整 */
  :deep(.el-form-item:nth-child(1) .el-form-item__label),
  :deep(.el-form-item:nth-child(2) .el-form-item__label),
  :deep(.el-form-item:nth-child(3) .el-form-item__label) {
    padding-left: 0px !important;
    /* 手机设备保持左对齐 */
    text-indent: 0px !important;
  }

  /* 手机设备表单项间距调整 */
  :deep(.el-form-item) {
    margin-bottom: 18px !important;
  }

  /* 手机设备输入框调整 */
  :deep(.el-input__wrapper) {
    min-height: 40px !important;
    padding: 10px 12px !important;
  }

  /* 手机设备按钮调整 */
  .login-btn,
  .cancel-btn {
    min-height: 40px !important;
    padding: 10px 24px !important;
    font-size: 14px !important;
  }

  /* 手机设备按钮间距调整 */
  :deep(.el-form-item:last-child .el-form-item__content) {
    gap: 8px !important;
  }
}

/* 特别小的屏幕或者屏幕高度不足时的优化 */
@media (max-height: 600px) {
  .login-container {
    padding: 20px 10px 15px !important;
  }

  .welcome-text {
    margin-bottom: 20px !important;
    margin-top: 0px !important;
  }

  .welcome-text h1 {
    font-size: 1.8rem !important;
  }

  .login-card {
    margin-bottom: 10px !important;
    padding: 20px 15px !important;
  }
}

/* 极小屏幕高度优化 */
@media (max-height: 500px) {
  .welcome-text {
    margin-bottom: 15px !important;
  }

  .welcome-text h1 {
    font-size: 1.5rem !important;
  }

  .login-card {
    padding: 15px !important;
  }

  :deep(.el-form-item) {
    margin-bottom: 15px !important;
  }
}

/* 验证码容器 */
.captcha-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.captcha-input {
  flex: 1;
}

.captcha-question {
  width: 120px;
  padding: 12px 8px;
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  text-align: center;
  font-weight: bold;
  color: #606266;
  cursor: pointer;
  user-select: none;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.captcha-question:hover {
  background-color: #eef1f6;
}
</style>